package top.raoqq.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.raoqq.sky.constant.SkyConstant;
import top.raoqq.sky.entity.sql.Role;
import top.raoqq.sky.entity.sql.User;
import top.raoqq.sky.enums.SkyResponseEnum;
import top.raoqq.sky.exception.BizException;
import top.raoqq.sky.mapper.RoleMapper;
import top.raoqq.sky.mapper.UserMapper;
import top.raoqq.sky.service.UserService;
import top.raoqq.sky.util.StringUtils;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * @author 饶奇奇
 * @date 2023/8/12
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final PasswordEncoder passwordEncoder;
    private final RoleMapper roleMapper;
    @Override
    public void listUserPageCondition(Page<User> page, String username, String phone, Byte status, LocalDate startTime, LocalDate endTime) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(username)) {
            wrapper.like(User::getUsername, username);
        }
        if (!StringUtils.isBlank(phone)) {
            wrapper.eq(User::getPhone, phone);
        }
        if (Objects.nonNull(status)) {
            wrapper.eq(User::getStatus, status);
        }
        //查询创建时间内要从大于等于开始日期的0点0分小于结束日期的后一天的0点0分
        if (Objects.nonNull(startTime)) {
            wrapper.ge(User::getCreateTime, startTime);
        }
        if (Objects.nonNull(endTime)) {
            wrapper.lt(User::getCreateTime, endTime.plusDays(1));
        }
        wrapper.orderByDesc(User::getCreateTime);
        wrapper.select(User.class, tableFieldInfo -> !"password".equals(tableFieldInfo.getColumn()));
        baseMapper.selectPage(page, wrapper);
        // 查询用户对应角色id集合
        List<User> userRoleDTOList = roleMapper.listRoleGroupByUserId();
        page.getRecords().forEach(user -> {
            userRoleDTOList.forEach(userRoleDTO -> {
                if (user.getId().equals(userRoleDTO.getId())) {
                    user.setRoleIdList(userRoleDTO.getRoleIdList());
                }
            });
        });
    }

    @Override
    public void saveOrUpdateUser(User user) {
        List<Long> roleIdList = user.getRoleIdList();
        Long id = user.getId();
        if (Objects.nonNull(id)) {
            // 如果id为空则是修改用户所以删除之前绑定的角色
            baseMapper.unBindRole(id);
            user.setPassword(null);
        } else {
            // 校验密码密码是否符合规范
            if (StringUtils.isBlank(user.getVisiblePassword()) || user.getVisiblePassword().length() < SkyConstant.PASSWORD_MIN_LENGTH) {
                throw new BizException(SkyResponseEnum.INPUT_PASSWORD_ERROR);
            }
            // 新增需要密码
            user.setPassword(passwordEncoder.encode(user.getVisiblePassword()));
        }
        // 校验角色Id是否合法
        if (!CollectionUtils.isEmpty(roleIdList)) {
            // 校验参数的合法性, 只要有一个角色id不存在都是错误
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Role::getId, roleIdList);
            if (!Long.valueOf(roleIdList.size()).equals(roleMapper.selectCount(wrapper))) {
                throw new BizException(SkyResponseEnum.SAVE_USER_ROLE_ID_NOT_EXISTS);
            }
        }
        // 保存或者修改用户
        saveOrUpdate(user);
        // 角色id合法并且不为空的情况下添加角色
        if (!CollectionUtils.isEmpty(roleIdList)) {
            baseMapper.bindRole(user.getId(), roleIdList);
        }
    }

    @Override
    public void switchUserStatus(Long userId, Byte status) {
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        baseMapper.updateById(user);
    }
}
